<?php

namespace App\Admin\Metrics\Examples;

use App\Models\Log\LogUserBrowse;
use App\Models\Log\LogUserCollect;
use App\Models\Search\Search;
use Dcat\Admin\Widgets\Metrics\Line;
use Illuminate\Http\Request;


class Collect extends Line
{
    /**
     * 初始化卡片内容
     *
     * @return void
     */
    protected function init()
    {
        parent::init();

        $this->title('最近收藏统计');
        $this->dropdown([
            '7' => '近7天',
            '30' => '近30天',
        ]);
    }

    /**
     * 处理请求
     *
     * @param Request $request
     *
     * @return mixed|void
     */
    public function handle(Request $request)
    {
        $search = LogUserCollect::where('created_at', '>', date("Y-m-d", time() - 86400 * 30))->orderby('created_at', 'desc')->pluck('created_at');
        $data = [];
        foreach(range(0, 30) as $v){
            $data[] = 0;
        }
        $today_time = strtotime(date("Y-m-d", time()));
        foreach($search as $v){
            $v_time = ceil(($today_time - strtotime(date("Y-m-d", strtotime($v)))) / 86400);
            $data[$v_time] += 1;
        }

        $generator = function ($len) use($data){
            for ($i = 0; $i <= $len; $i++) {
                yield $data[$i];
            }
        };

        switch ($request->get('option')) {
            case '30':
                // 卡片内容
                $this->withContent(array_sum($data), date("Y-m-d", time()) . ' ~ ' . date("Y-m-d", time() - 86400 * 30));
                // 图表数据
                $this->withChart(collect($generator(30))->toArray());
                break;
            case '7':
            default:
                // 卡片内容
                $this->withContent(array_sum(array_slice($data, 0, 7)), date("Y-m-d", time()) . ' ~ ' . date("Y-m-d", time() - 86400 * 7));
                // 图表数据
                $this->withChart(collect($generator(7))->toArray());
        }
    }

    /**
     * 设置图表数据.
     *
     * @param array $data
     *
     * @return $this
     */
    public function withChart(array $data)
    {
        return $this->chart([
            'series' => [
                [
                    'name' => $this->title,
                    'data' => $data,
                ],
            ],
        ]);
    }

    /**
     * 设置卡片内容.
     *
     * @param string $content
     *
     * @return $this
     */
    public function withContent($content, $title)
    {
        return $this->content(
            <<<HTML
<div class="d-flex justify-content-between align-items-center mt-1" style="margin-bottom: 2px">
    <h2 class="ml-1 font-lg-1">{$content}</h2>
    <span class="mb-0 mr-1 text-80">{$title}</span>
</div>
HTML
        );
    }
}
